﻿CREATE PROCEDURE [dbo].[InventoryDocDelete]
(
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intErrCode int, @intRet int, @orgDocTypeId int
DECLARE @intLineId int, @datLineMD datetime

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) 
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId 
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 6
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

DECLARE DocLines CURSOR FAST_FORWARD FOR
SELECT Id, MD FROM CD.InventoryLines WHERE DocId = @Original_Id

OPEN DocLines

FETCH NEXT FROM DocLines INTO @intLineId, @datLineMD
BEGIN TRAN
WHILE (@@FETCH_STATUS = 0)
BEGIN

		EXEC @intRet = dbo.InventoryLinesDelete @intLineId, @datLineMD
	
		SET @intErrCode = @@error
		IF @intErrCode <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE DocLines
			DEALLOCATE DocLines
			RETURN @intErrCode
		END
		
		IF @intRet <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE DocLines
			DEALLOCATE DocLines
			RETURN @intRet
		END
	
	FETCH NEXT FROM DocLines INTO @intLineId, @datLineMD
END

CLOSE DocLines
DEALLOCATE DocLines

	SET NOCOUNT OFF;
DELETE FROM [CA].[Documents] WHERE Id = @Original_Id AND MD = @Original_MD

COMMIT TRAN






